<?php

namespace App\Http\Controllers\ZHIHU\Systems;

use DB;
use App\Http\Controllers\ZHIHU\ApiController;
use Illuminate\Http\Request;
use Carbon\Carbon;
use App\Eloqumd\Zhihu\ZhihuUser;
use App\Eloqumd\Zhihu\ZhihuTopic;
use App\Eloqumd\System\SysPv;
use App\Eloqumd\System\SysUv;
use App\Eloqumd\System\SysVisit;

class SystemStatisController extends ApiController
{
    protected function diffAddtionOfArr($res, $combileKey, $combileArr, $addtionKey)
    {
        $categorieKey = array_column($res, $combileKey);
        $diff = array_diff($combileArr, $categorieKey);
        if ($diff) {
            $diff = array_values($diff);
            array_map(function ($v) use (&$fillDiff, $combileKey, $addtionKey) {$fillDiff[] = [$combileKey => $v, $addtionKey => 0];}, $diff);
            $res = array_merge($res, $fillDiff);
        }
        uasort($res, function ($a, $b) use ($combileKey) {
            $a = (array)$a;
            $b = (array)$b;
            if ($a[$combileKey] == $b[$combileKey]) return 0;
                return ($a[$combileKey] < $b[$combileKey]) ? -1 : 1;
        });

        return $res;
    }
    // 用户注册量统计
    public function userRegisterCharts(Request $request)
    {
        $dateStep = $request->input('datestep', '');
        $type = $request->input('type', '');

        $categories = [];
        if ($dateStep) {
            $startDate = $dateStep[0];
            $endDate = $dateStep[1];
            $start = Carbon::parse($startDate);
            $end = Carbon::parse($endDate);
            $diffDt = clone($end);
            $diffYm = 0;
            if ($endDate != $startDate) {
                $diff = $start->diff($end);
                $diffYm = $diff->format('%y') * 12 + $diff->format('%m');
            }
        } else {
            $dt = Carbon::today();
            $diffDt = clone($dt);
            $endDate = $dt->format('Y-m');
            $startDate = $dt->subMonth(12)->format('Y-m');
            $diffYm = 12;
        }

        array_push($categories, $endDate);
        for ($i = 1; $i <= $diffYm; $i ++) {
            array_push($categories, $diffDt->subMonth()->format('Y-m'));
        }
        sort($categories);

        $querySql = "select created_at as categorie,count(created_at) as nums from (select left(created_at, 7) as created_at from yw_zhihu_users where user_type=1 and  left(created_at, 7) between :startDate and :endDate HAVING left(created_at, 7)) c GROUP BY created_at";
        $res = DB::select($querySql, ['startDate' => $startDate, 'endDate' => $endDate]);

        $res = $this->diffAddtionOfArr($res, 'categorie', $categories, 'nums');

        $jsonData = [
            'categories' => $categories,
            'seriesData' => array_column($res, 'nums')
        ];

        if ($type == 2) {
            array_map(function ($v) use (&$seriesData) {
                $v = (array)$v;
                $seriesData[] = ['name' => $v['categorie'], 'y' => $v['nums']];
            }, array_values($res));
            $jsonData = [
                'categories' => $categories,
                'seriesData' => $seriesData
            ];
        }

        return $this->jsonReturns(10000, $this->success, $jsonData, 'chart');
    }

    // PUV统计
    public function puvCharts(Request $request)
    {
        $type = $request->input('type', '1');

        $categories = [];

        switch ($type) {
            case '1':
                $dt = Carbon::now();
                $diffDt = clone($dt);
                $endDate = $dt->format('Y-m-d');
                $startDate = $dt->subDay(6)->format('Y-m-d');
                $diffYmd = 6;
                $format = '%Y-%m-%d';
                array_push($categories, $endDate);
                for ($i = 1; $i <= $diffYmd; $i ++) {
                    array_push($categories, $diffDt->subDay()->format('Y-m-d'));
                }
                break;
            case '2':
                $dt = Carbon::now();
                $diffDt = clone($dt);
                $endDate = $dt->format('Y-m-d');
                $startDate = $dt->subDay(29)->format('Y-m-d');
                $diffYmd = 29;
                $format = '%Y-%m-%d';
                array_push($categories, $endDate);
                for ($i = 1; $i <= $diffYmd; $i ++) {
                    array_push($categories, $diffDt->subDay()->format('Y-m-d'));
                }
                break;
            case '3':
                $dt = Carbon::now();
                $diffDt = clone($dt);
                $endDate = $dt->format('Y-m');
                $startDate = $dt->subMonth(5)->format('Y-m');
                $diffYm = 5;
                $format = '%Y-%m';
                array_push($categories, $endDate);
                for ($i = 1; $i <= $diffYm; $i ++) {
                    array_push($categories, $diffDt->subMonth()->format('Y-m'));
                }
                break;
            case '4':
                $dt = Carbon::now();
                $diffDt = clone($dt);
                $endDate = $dt->format('Y-m');
                $startDate = $dt->subMonth(11)->format('Y-m');
                $diffYm = 11;
                $format = '%Y-%m';
                array_push($categories, $endDate);
                for ($i = 1; $i <= $diffYm; $i ++) {
                    array_push($categories, $diffDt->subMonth()->format('Y-m'));
                }
                break;
            default:
                return $this->jsonReturns(10000, $this->success, [
                    'categories' => [],
                    'seriesData' => [],
                    'PUV' => []
                ]);
                break;
        }

        sort($categories);

        $resPV = SysPv::select(DB::raw('count(*) as nums'), DB::raw("FROM_UNIXTIME(last_time, \"$format\") as categorie"))
            ->where('puv', 'zhihu')
            ->whereBetween(DB::raw("FROM_UNIXTIME(last_time, \"$format\")"), [$startDate, $endDate])
            ->groupBy(DB::raw("FROM_UNIXTIME(last_time, \"$format\")"))
            ->get()
            ->toArray();

        $resPV = $this->diffAddtionOfArr($resPV, 'categorie', $categories, 'nums');
        $seriesData[] = [
            'name' => 'PV',
            'data' => array_column($resPV, 'nums')
        ];

        $resUV = SysUv::select(DB::raw('count(*) as nums'), DB::raw("FROM_UNIXTIME(last_time, \"$format\") as categorie"))
            ->where('puv', 'zhihu')
            ->whereBetween(DB::raw("FROM_UNIXTIME(last_time, \"$format\")"), [$startDate, $endDate])
            ->groupBy(DB::raw("FROM_UNIXTIME(last_time, \"$format\")"))
            ->get()
            ->toArray();

        $resUV = $this->diffAddtionOfArr($resUV, 'categorie', $categories, 'nums');
        $seriesData[] = [
            'name' => 'UV',
            'data' => array_column($resUV, 'nums')
        ];

        $jsonData = [
            'categories' => $categories,
            'seriesData' => $seriesData,
            'PUV' => SysVisit::where('puv', 'zhihu')->first()->toArray()
        ];

        return $this->jsonReturns(10000, $this->success, $jsonData, 'chart');
    }

    // 话题量统计
    public function topicCharts(Request $request)
    {
        $topicData = ZhihuTopic::where('status', 1)->get()->toArray();
        $categories = array_column($topicData, 'name');

        $seriesColumnQData = [];
        $seriesColumnFData = [];
        array_map(function ($v) use (&$seriesColumnQData, &$seriesColumnFData) {
            array_push($seriesColumnQData, (int)$v['questions_count']);
            array_push($seriesColumnFData, (int)$v['followers_count']);
        }, $topicData);

        $qName = trans('zhihu.Statis-Question-Name');
        $fName = trans('zhihu.Statis-Follower-Name');
        $qfSumName = trans('zhihu.Statis-Question-Follower-Sum-Name');
        $seriesData[] = ['type' => 'column', 'name' => $qName, 'data' => $seriesColumnQData];
        $seriesData[] = ['type' => 'column', 'name' => $fName, 'data' => $seriesColumnFData];
        $seriesData[] = ['type' => 'spline', 'name' => $qName, 'data' => $seriesColumnQData];
        $seriesData[] = ['type' => 'spline', 'name' => $fName, 'data' => $seriesColumnFData];
        $seriesData[] = ['type' => 'pie', 'name' => $qfSumName, 'data' => [
            ['name' => $qName, 'y' => array_sum($seriesColumnQData)],
            ['name' => $fName, 'y' => array_sum($seriesColumnFData)]
        ]];

        $jsonData = [
            'categories' => $categories,
            'seriesData' => $seriesData,
        ];

        return $this->jsonReturns(10000, $this->success, $jsonData, 'chart');
    }

    // 活跃度分析
    public function activityCharts(Request $request)
    {
        $limitType = $request->input('limitType', '1');
        $dateType = $request->input('dateType', '1');

        $queryUserInfoSql = "SELECT count(log_user_id) as totalNums,log_user_id,log_user_name as name FROM `yw_browse_logs` where log_k='zhihu' ";
        $querySubSql = "SELECT count(log_type) as value,log_type_trans as name FROM `yw_browse_logs` where log_k='zhihu' and log_user_id=:log_user_id  ";
        $dt = Carbon::now();
        switch ($dateType) {
            case '1':
                $endDate = $dt->format('Y-m-d');
                $startDate = $dt->subDay(6)->format('Y-m-d');
                $hasSE = 1;
                break;
            case '2':
                $endDate = $dt->format('Y-m-d');
                $startDate = $dt->subMonth()->format('Y-m-d');
                $hasSE = 1;
                break;
            case '3':
                $endDate = $dt->format('Y-m-d');
                $startDate = $dt->subMonth(3)->format('Y-m-d');
                $hasSE = 1;
                break;
            case '4':
                $endDate = $dt->format('Y-m-d');
                $startDate = $dt->subMonth(6)->format('Y-m-d');
                $hasSE = 1;
                break;
            case '5':
                $endDate = $dt->format('Y-m-d');
                $startDate = $dt->subMonth(12)->format('Y-m-d');
                $hasSE = 1;
                break;
            default:
                $hasSE = 0;
                break;
        }

        $sdik = [];
        if ($hasSE) {
            $queryUserInfoSql .= "and left(log_created_at, 10) between :startDate and :endDate ";
            $querySubSql .= "and left(log_created_at, 10) between :startDate and :endDate ";
            $sdik = ['startDate' => $startDate, 'endDate' => $endDate];
        }

        $queryUserInfoSql .= "GROUP BY log_user_id,log_user_name ";
        $queryUserInfoSql .= "ORDER BY count(log_user_id) desc ";
        $querySubSql .= "GROUP BY log_type,log_type_trans;";

        switch ($limitType) {
            case '1':
                $queryUserInfoSql .= "limit 3;";
                break;
            case '2':
                $queryUserInfoSql .= "limit 10;";
                break;
            default:
                $queryUserInfoSql .= ";";
                break;
        }
        $jsonData = DB::select($queryUserInfoSql, $sdik);

        foreach ($jsonData as $k => $v) {
            $sdik['log_user_id'] = $v->log_user_id;
            $data = DB::select($querySubSql, $sdik);
            $jsonData[$k]->data = $data;
        }

        return $this->jsonReturns(10000, $this->success, $jsonData, 'chart');
    }
}
